package com.itheima.servlet;

import com.itheima.utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet(urlPatterns="/lastCookie")
public class LastTimeCookie extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        Cookie cookie = CookieUtils.findByName("lastTime", cookies);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if (cookie!=null){
            String time = cookie.getValue();
            writer.write("<h3>欢迎再次光临,上次访问时间是"+time+"</h3>");
        }else{
            writer.write("<h3>欢迎首次访问</h3>");
        }
        Cookie c = new Cookie("lastTime", new Date().toLocaleString().replaceAll(" ", ""));
        c.setMaxAge(60*60*24*3);
        response.addCookie(c);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}